import React from 'react'
import { Navigate } from 'react-router-dom'

interface ProtectedRouteProps {
  children: React.ReactNode
  requireAuth?: boolean // 是否需要登录
  redirectTo?: string // 未登录时跳转的路径
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ 
  children, 
  requireAuth = true, 
  redirectTo = '/login' 
}) => {
  const token = localStorage.getItem('userToken')
  const isAuthenticated = !!token

  // 如果需要登录但未登录，跳转到登录页
  if (requireAuth && !isAuthenticated) {
    return <Navigate to={redirectTo} replace />
  }

  // 如果已登录但访问登录/注册页，跳转到首页
  if (!requireAuth && isAuthenticated) {
    return <Navigate to="/index" replace />
  }

  return <>{children}</>
}

export default ProtectedRoute
